/*jslint vars: true, forin: true, sloppy: true */
/*global angular, ocDialog, DialogManager, DialogFactory */
ocDialog.directive('ocTabSet', function () {
	return {
		restrict: 'E',
		transclude: true,
		replace: true,
		scope: {
			control: "=?ocTabControl"
		},
		controller: function ($scope) {
			$scope.tabs = [];
			$scope.control = $scope.control || {};
			$scope.control.selected = $scope.control.selected || 0;

			this.registerTab = function (tab) {
				// Param 'tab' is a isolating scope of the 'ocTab' directive.
				var index = $scope.tabs.push(tab);
				tab.index = index - 1;
				tab.control = $scope.control;
			};
		},
		template:
			'<div class="oc-tabs">' +
				'<ul><li ng-repeat="tab in tabs" ng-class="{active:control.selected==$index}">' +
				'<button ng-click="select($index)" title="{{tab.ocTabTitle}}" ng-disabled="tab.isDisabled"' +
				'>{{tab.ocTabTitle}}</button></li></ul>' +
				'<div class="oc-tab-content" ng-transclude></div>' +
			'</div>',
		link: function (scope, element, attrs) {
			scope.control.$tabs = scope.tabs;

			scope.select = function (index) {
				scope.control.selected = index;
			};

			scope.$watch('control.selected', function () {
				var tab = scope.tabs[scope.control.selected];
				(tab.selectFn || angular.noop).call(scope, tab);
			});
		}
	};
}).directive('ocTab', function () {
	return {
		require: '^ocTabSet',
		restrict: 'E',
		transclude: true,
		replace: true,
		scope: {
			ocTabTitle: '@',
			selectFn: '=?ocTabActiveFn'
		},
		link: function (scope, element, attrs, ctrl) {
			ctrl.registerTab(scope);
		},
		template: '<section ng-transclude ng-show="index==control.selected"></section>'
	};
});
